<template>
  <div id="invite">

    <Myheader :page="page"></Myheader>

    <div class="card" v-if="!show">
      <form-preview header-label="邀请码" :header-value="invitationMessage.code" :body-items="list" footer-buttons="">
      </form-preview>

    </div>

    <div v-if="show">
      <group title="使用邀请码">
        <x-input title="输入赛事id" v-model="raceId"></x-input>
        <x-input title="输入邀请码" v-model="invitationCode"></x-input>
        <div style="padding-left:15px;padding-right:15px;">
          <x-button @click.native="onSubmit" type="primary">确定</x-button>
        </div>

      </group>

      <!-- <search v-model="invitationCode" position="static" @on-submit="onSubmit" :autoFixed=false ref="search"></search> -->
    </div>

    <div class="button_header" id='x-bottom'>
      <x-header slot="header" style="width: 100%;position: fixed;bottom: 0px;z-index: 100;max-width: 850px;margin: 0 auto;" title="去报名" @on-click-title='useInvite'>
        <div slot="overwrite-left"></div>

      </x-header>

    </div>

  </div>
</template>


<script type="text/ecmascript-6">
/* eslint-disable*/

import { cookie } from "vux";

import Myheader from "@/common/components/myheader.vue";

import { getForm } from "@/api/getForm.js";

import {
  Card,
  XButton,
  FormPreview,
  Search,
  XInput,
  Group,
  XHeader
} from "vux";

import { indexedDB } from "@/api/indexedDB.js";

import { setTitle } from "@/common/js/main.js";

// 获取项目列表
//axios
import qs from "qs";
import { axios } from "@/api/axios.js";
import mixin from "@/common/js/mixin";
export default {
  mixins: [mixin],
  props: ["page", "host"],
  data() {
    return {
      raceId: "",
      show: false,
      invitationCode: "", //邀请码
      inviteRaceid: "", //限制赛事
      invitationEventId: "", //限制项目
      invitationMessage: {},
      state: 0,
      stateMessage: "不可使用",
      disabled: true,
      list: [],
      buttons: [],
      invitationDiscount: ""
    };
  },
  beforeCreate() {
    setTitle("邀请码");
  },
  created() {
    var test = window.location.href;
    if (test.match(/invite.+/) != null && test.match(/invite.+/) != "invite/") {
      var code;
      if (test.indexOf("_sid") != -1) {
        code = test.match(/invite.+\?/g);
        code = code[0];
        code = code.slice(0, code.length - 1);
        code = code.substring(7);
      } else {
        code = test.match(/invite.+/g);
        code = code[0];
        code = code.substring(7);
      }
      this.show = false;
      const invitationCode = code;
      this.raceId = this.page.raceid;
      this.invitationCode = invitationCode;
      this.postInvite();
    } else {
      this.show = true;
    }
    //  console.log(this.$route.query.raceid)
    //  console.log(this.$route.query.invitationCode)
    // if (!!(this.$route.query.raceid)&&!!(this.$route.query.invitationCode)) {

    //   this.raceId = this.$route.query.raceid
    //   this.invitationCode = this.$route.query.invitationCode
    //   this.postInvite();
    // } else {
    //   this.show = true;
    // }
  },
  mounted() {},
  methods: {
    onSubmit(a) {
      if (!this.raceId && !this.invitationCode) {
        return;
      }

      //this.$router.push({ path: `/invite?raceid=${this.raceId}&invitationCode=${this.invitationCode}`});
      //this.postInvite();
    },
    useInvite() {
      if (!!this.disabled) {
        return;
      }

      window.localStorage.setItem(
        "invitationRaceId",
        this.invitationMessage.raceid
      );

      window.localStorage.setItem(
        "invitationDiscount",
        this.invitationDiscount
      );

      window.localStorage.setItem("invitationCode", this.invitationCode);

      window.localStorage.setItem(
        "invitationEventId",
        this.invitationMessage.eventid
      );

      window.localStorage.setItem("invitationEventName", this.eventName);

      this.$router.push({ path: `/list?race_id=${this.raceId}` });
      // indexedDB('invite', 'set', this.RACEID, {
      //   invitationCode: this.invitationCode,
      //   invitationEventId: this.invitationEventId
      // }, (a) => {
      //   this.$router.push({path: '/list'});
      // })
    },
    _getRace(id) {
      //获取赛事
      return this.axios.post(
        `${window.host}race/show`,
        qs.stringify({
          raceid: id
        })
      );
    },
    _getEvent(id) {
      //获取项目
      return this.axios.post(
        `${window.host}event/show`,
        qs.stringify({
          eventid: id
        })
      );
    },
    _getInvite() {
      //获取邀请码
      return this.axios.post(
        `${window.host}invite/show`,
        qs.stringify({
          raceid: this.page.raceid,
          invite: this.invitationCode,
          json: 1
        })
      );
    },
    postInvite() {
      this.axios
        .post(
          `${window.host}invite/show`,
          qs.stringify({
            raceid: this.raceId,
            invite: this.invitationCode,
            json: 1
          })
        )
        .then(response => {
          if (response.data.code == 200) {
            this.show = false;
            this.invitationMessage = response.data.data;

            /*mock*/
            //过期时间
            /* this.invitationMessage.expired_at = '2019-1-1'*/
            //已经使用次数
            /*this.invitationMessage.used_times = 3*/
            //可以使用次数
            /*this.invitationMessage.times = 3*/
            /**/

            //mock数据
            /*this.invitationMessage = {
             "id": 1,
             "raceid": 11,
             "eventid": 1,
             "code": "ERBY-G6O8-UOPQ-EFMC",
             "name": "无锡马拉松组委会",
             "idnum": "12121212121",
             "times": 10,
             "used_times": 100,
             "discount": 0,
             "expired_at": "2018-01-12 15:24:14",
             "used_at": null,
             "short_link": null,
             "created_at": "2018-01-04 15:24:19",
             "updated_at": "2018-01-04 15:24:19",
             "deleted_at": null
             }*/

            this.inviteRaceid = this.invitationMessage.raceid;
            this.invitationEventId = this.invitationMessage.eventid;
            this.invitationDiscount = this.invitationMessage.discount;

            this.axios
              .all([
                this._getEvent(this.invitationEventId),
                this._getRace(this.inviteRaceid)
              ])
              .then(
                axios.spread((res1, res2) => {
                  this.eventName = res1.data.data.name || "任意项目";
                  this.raceName = res2.data.data.name;

                  //如果使用次数不填 自动设0
                  if (this.invitationMessage.used_times == null) {
                    this.invitationMessage.used_times = 0;
                  }

                  let nowTime = new Date().valueOf();
                  //response.data.data.expired_at='2016-11-1 10:00:00'
                  let expiredTime = new Date(
                    this.invitationMessage.expired_at
                  ).valueOf();

                  if (
                    this.invitationMessage.expired_at === null &&
                    this.invitationMessage.used_times <
                      this.invitationMessage.times
                  ) {
                    //不限制时间而且次数可以使用
                    this.invitationMessage.expired_at = "不限制时间";
                    this.stateMessage = "不限制时间";
                    this.disabled = false;
                  } else if (
                    this.invitationMessage.expired_at === null &&
                    this.invitationMessage.times === null
                  ) {
                    //次数和时间不限制
                    this.disabled = false;
                    this.invitationMessage.expired_at = "不限制时间";
                    this.invitationMessage.times = "不限制次数";
                  } else if (
                    this.invitationMessage.expired_at === null &&
                    this.invitationMessage.used_times >=
                      this.invitationMessage.times
                  ) {
                    //不限制时间但是次数用完了
                    this.stateMessage = "次数用完了";
                    this.disabled = true;
                    this.invitationMessage.expired_at = "不限制时间";
                  } else if (
                    this.invitationMessage.times == null &&
                    expiredTime <= nowTime
                  ) {
                    //不限制次数但是时间过期了
                    this.stateMessage = "过期了";
                    this.invitationMessage.times = "不限制次数";
                    this.disabled = true;
                  } else if (
                    this.invitationMessage.times == null &&
                    expiredTime > nowTime
                  ) {
                    //不限制次数并且时间没有过期
                    this.stateMessage = "去使用";
                    this.invitationMessage.times = "不限制次数";
                    this.disabled = false;
                  } else if (expiredTime <= nowTime) {
                    this.stateMessage = "过期了";
                    this.disabled = true;
                  } else if (
                    this.invitationMessage.times <=
                    this.invitationMessage.used_times
                  ) {
                    this.stateMessage = "次数用完了";
                    this.disabled = true;
                  } else {
                    this.stateMessage = "去使用";
                    this.disabled = false;
                  }

                  /*        //如果时间不限而且次数没到期
                 if (res1.data.data.expired_at == null && this.invitationMessage.used_times <= this.invitationMessage.times) {
                 alert(1)
                 this.stateMessage = '不限时间'
                 this.invitationMessage.expired_at = '不限时间'
                 this.disabled = false
                 }
                 //如果次数不限而且时间没到期
                 if (this.invitationMessagetimes == null && expiredTime <= nowTime) {
                 alert(2)
                 this.stateMessage = '去使用'
                 this.invitationMessage.expired_at = res1.data.data.expired_at
                 this.disabled = false
                 }
                 //时间和次数都没限制
                 if (res1.data.data.expired_at == null && res1.data.data.times == null) {
                 alert(3)
                 this.stateMessage = '去使用'
                 this.invitationMessage.times = '不限次数'
                 this.invitationMessage.expired_at = '不限时间'
                 this.disabled = false
                 }*/

                  let lists = [
                    {
                      label: "限制报名赛事",
                      value: `${this.raceName}`
                    },
                    {
                      label: "限制项目",
                      value: `${this.eventName}`
                    },
                    {
                      label: "有效次数",
                      value: `${this.invitationMessage.times}`
                    },
                    {
                      label: "已使用次数",
                      value: `${this.invitationMessage.used_times}`
                    },
                    {
                      label: "过期时间",
                      value: `${this.invitationMessage.expired_at}`
                    }
                  ];

                  this.list = lists;

                  if (!this.disabled) {
                    //可以使用邀请码
                    this.buttons = [
                      {
                        style: "primary",
                        text: "使用该邀请码报名",
                        onButtonClick: name => {
                          this.useInvite();
                        }
                      }
                    ];
                  } else {
                    //不可以使用邀请码
                    this.buttons = [
                      {
                        style: "default",
                        text: "使用该邀请码报名"
                      }
                    ];
                  }

                  if (this.stateMessage == "过期了") {
                    let _this = this;
                    setTimeout(function() {
                      let mylists = document.querySelectorAll(
                        ".weui-form-preview__value"
                      );
                      mylists[5].innerHTML = `${
                        _this.invitationMessage.expired_at
                      }<span class="expired">(过期了)</span>`;
                    }, 0);
                  }

                  if (this.stateMessage == "次数用完了") {
                    let _this = this;
                    setTimeout(function() {
                      let mylists = document.querySelectorAll(
                        ".weui-form-preview__value"
                      );
                      mylists[4].innerHTML = `${
                        _this.invitationMessage.used_times
                      }<span class="expired">(次数用完了)</span>`;
                    }, 0);
                  }

                  // setTimeout(function() {
                  //   var newNode = document.createElement("p");
                  //   let bd = document.querySelector(".weui-form-preview__bd");
                  //   newNode.innerHTML =
                  //     '<p style="color:red;text-align: left">如果之前在官网报过名，进入官网—在报名查询中输入选手证件号码——根据短信提示进行报名</p>';
                  //   bd.appendChild(newNode);
                  // }, 0);
                })
              );
          } else {
            this.$vux.toast.show({
              text: response.data.msg,
              type: "warn"
            });
          }
        });
    }
  },
  components: {
    XHeader,
    Card,
    XButton,
    FormPreview,
    Myheader,
    Search,
    XInput,
    Group
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" rel="stylesheet/less">
html,
body {
  width: 100%;
  height: 100%;
}

#invite .weui-form-preview__hd .weui-form-preview__value {
  font-size: initial;
}

#invite .card {
  padding-top: 20px;
  padding-left: 10px;
  padding-right: 10px;
  .weui-panel {
    border-radius: 10px;
  }
}

#invite .expired {
  color: red;
}

#invite .content-right {
  position: absolute !important;
  right: 25px;
}

#invite {
  min-height: 560px;
  .card-padding {
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    color: currentColor !important;
    padding: 25px 25px 0;
    min-height: 96px;
    box-sizing: border-box;
    background-color: #fff;
    .content-left {
      width: 120px;
      text-align: center;
      position: relative;
      display: -webkit-box;
      display: -webkit-flex;
      display: flex;
      -webkit-box-orient: vertical;
      -webkit-box-direction: normal;
      -webkit-flex-direction: column;
      flex-direction: column;
      -webkit-box-pack: center;
      -webkit-justify-content: center;
      justify-content: center;
      margin-right: 10px;
      vertical-align: top;
      i {
        font-size: 14px;
        display: inline-block;
        vertical-align: top;
        margin: 6px 4px 0 0;
      }
      srong {
        font-family: font_steelfish;
        font-weight: 700;
        font-size: 45px;
        position: relative;
        top: 1px;
      }
    }
    .content-right {
      -webkit-box-flex: 1;
      -webkit-flex: 1;
      flex: 1;
      min-width: 0;
      position: relative;
      padding-bottom: 15px;
    }
  }
  .card-padding > div {
    display: inline-block;
  }
}

.hide {
  /*display: none;*/
  opacity: 0;
}

.draw-gift {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.draw-gift .draw-img {
  width: 100%;
  position: relative;
  margin-top: 6.5rem;
}

.draw-gift .draw-img .draw-down {
  position: absolute;
  width: 9rem;
  height: 9.9rem;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url(//www.17sucai.com/preview/1/2017-11-02/hb/image/open-no.png);
  left: 50%;
  margin-left: -4.5rem;
  z-index: 10;
  /*-webkit-animation:draw-down 0.5s ease 1.2s 1 alternate;*/
  /*-webkit-animation-timing-function:cubic-bezier(0.25,0.1,0.25,1);*/
}

@-webkit-keyframes draw-down {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 0;
  }
}

.draw-gift .draw-img .draw-down2 {
  position: absolute;
  width: 9rem;
  height: 9.9rem;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url(//www.17sucai.com/preview/1/2017-11-02/hb/image/open-before.png);
  left: 50%;
  margin-left: -4.5rem;
  z-index: 10;
  /*-webkit-animation:draw-down2 0.5s ease 1.4s 1 alternate;*/
  /*-webkit-animation-timing-function:cubic-bezier(0.25,0.1,0.25,1);*/
}

@-webkit-keyframes draw-down2 {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}

.draw-gift .draw-img .draw-mid {
  position: absolute;
  width: 3rem;
  height: 3rem;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url(//www.17sucai.com/preview/1/2017-11-02/hb/image/open.png);
  left: 50%;
  margin-left: -1.5rem;
  z-index: 100;
  top: 3.1rem;
  /*animation:open 0.3s linear 1s 3 alternate;*/
}

.draw-gift .draw-img .draw-mid-move {
  -webkit-animation: open 0.2s linear 0.5s infinite alternate;
  -webkit-animation-timing-function: cubic-bezier(0.25, 0.1, 0.25, 1);
  animation: open 0.2s linear 0.5s infinite alternate;
  animation-timing-function: cubic-bezier(0.25, 0.1, 0.25, 1);
}

@keyframes open {
  0% {
    transform: scale(1);
  }
  100% {
    transform: scale(0.9);
  }
}

@-webkit-keyframes open {
  0% {
    -webkit-transform: scale(1);
  }
  100% {
    -webkit-transform: scale(0.9);
  }
}

.draw-gift .draw-img .draw-up {
  position: absolute;
  width: 9rem;
  height: 4.15rem;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url(//www.17sucai.com/preview/1/2017-11-02/hb/image/open-back-1.png);
  left: 50%;
  margin-left: -4.5rem;
  top: 0.6rem;
  z-index: 8;
  opacity: 0;
}

.draw-gift .draw-img .draw-up-up {
  position: absolute;
  width: 9rem;
  height: 4.12rem;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url(//www.17sucai.com/preview/1/2017-11-02/hb/image/open-back-2.png);
  left: 50%;
  margin-left: -4.5rem;
  top: 0;
  /*-webkit-transform: rotateX(180deg);*/
  /*-webkit-transform-style: flat;*/
  /*-webkit-transform-origin: bottom;*/
  /*-webkit-animation: draw-up-up 1s linear 0s 0.5 normal;*/
  /*backface-visibility: visible;*/
  /*-webkit-animation-timing-function:cubic-bezier(0.25,0.1,0.25,1);*/
  opacity: 0;
  z-index: 3;
  transition: all 0.5s;
}

.draw-gift .draw-img .draw-list {
  position: absolute;
  width: 5rem;
  height: 6rem;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url(//www.17sucai.com/preview/1/2017-11-02/hb/image/draw-list-bg.jpg);
  left: 50%;
  margin-left: -2.5rem;
  top: 3.5rem;
  opacity: 0;
  z-index: 8;
}

.draw-gift .draw-img .draw-list img {
  vertical-align: middle;
  position: absolute;
  width: 70%;
  top: 1.6rem;
  left: 15%;
}

#draw-btn {
  position: absolute;
  width: 100%;
  text-align: center;
  font-size: 0.65rem;
  color: #333;
  top: 17rem;
}

.draw-img p {
  text-align: center;
}

#invite .vux-search-fixed {
  position: static;
}
</style>








